package com.efounder.form.comp;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.DataSetListener;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.form.DMColComponent;
import com.efounder.form.DMComponent;
import com.efounder.form.DataSetComponent;
import com.efounder.form.base.IComponent;
import com.efounder.form.model.JSONFormModel;
import com.efounder.form.model.MDModel;
import com.efounder.form.util.FormCompUtil;
import com.efounder.frame.ViewSize;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import cn.qqtheme.framework.picker.OptionPicker;

/***
 * auto by lch
 * TODO 目前是一级的，并且没有关联datamodel
 */
public class FormDataSetFieldComboBox_old extends TextView implements IComponent,IUIComponent,DMComponent,DMColComponent,DataSetListener {

	private String originalText;
	private Boolean editable = true;

	private int gap;

	private String dataSetID;
	private String dataSetColID;

	private String valueDataSetColID;
	private String viewDataSetColID;
	private String viewDataSetID;

	private String horizontalAlign;
	private String verticalAlign;

	private DataSetComponent dataSetComponent;
	private EFDataSet dataSet;
	private EFRowSet mainRowSet;

	private MDModel mdModel;

	private IUIComponent parentComp;


	private ViewSize size = new ViewSize(0, 0);

	private Context context;
	private String imageUrl ="http://oap8mw8pg.bkt.clouddn.com/FndmI1RMqRYuwYSI2ouMu3pM4zEv";
	//private String imageUrl =" http://tupian.qqjay.com/tou3/2016/0725/cb00091099ffbf09f4861f2bbb5dd993.jpg";

	public FormDataSetFieldComboBox_old() {
//		super(AppContext.getInstance());
//		this.context = AppContext.getInstance();
		super(AppContext.getInstance());
		this.context = AppContext.getInstance();
		this.setTextColor(Color.BLACK);
	}

	public FormDataSetFieldComboBox_old(Context context) {
		super(context);
		this.context = AppContext.getInstance();
	}
	public FormDataSetFieldComboBox_old(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = AppContext.getInstance();
	}

	@Override
	public void setLayout() {

	}

	private void showToast(String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}

	private String value;
	private EFDataSet mdDataSet;
	public void dataChanged(EFDataSet dataSet) {
		if(dataSet.getTableName().equals(dataSetID)) {
			//formmodel
			mainRowSet = dataSet.getCurrentRowSet();
			if (mainRowSet != null) {
				value = mainRowSet.getString(dataSetColID, "");
			}
		}else if(dataSet.getTableName().equals(viewDataSetID)) {
			//mdmodel
			if (mdModel == null) return;
			mdDataSet = mdModel.getMdmDataModel().getDataSet(viewDataSetID);
		}
		initByDataSet(mdDataSet,value);

	}

	public String getOriginalText() {
		return originalText;
	}

	public void setOriginalText(String originalText) {
		this.originalText = originalText;

		this.setText(originalText);
	}

	@Override
	public DataSetComponent getDataSetComponent() {
		return dataSetComponent;
	}

	@Override
	public void setDataSetComponent(DataSetComponent dsc) {
		if (dataSetComponent != null)
			dataSetComponent.removeDMComponent(this);
		dataSetComponent = dsc;
		if (dataSetComponent != null)
			dataSetComponent.insertDMComponent(this);
	}

	public void setDataSetComponent(JSONFormModel dsc) {
		if (dataSetComponent != null)
			dataSetComponent.removeDMComponent(this);
		dataSetComponent = dsc;
		if (dataSetComponent != null)
			dataSetComponent.insertDMComponent(this);
	}

	@Override
	public void creationComplete() {

		FormCompUtil.setLayoutSize(this);
		this.setGravity(FormCompUtil.getLayoutGravity(horizontalAlign, verticalAlign));

		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.width= this.getViewSize().getWidth();
		layoutParams.height = this.getViewSize().getHeight();
		this.setLayoutParams(layoutParams);

        this.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);

        if(imageUrl.equals("")){
            Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_help_search);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            FormDataSetFieldComboBox_old.this.setCompoundDrawables(null,null,rightDrawable,null);
        }else {
            new DownloadImageTask().execute(imageUrl);
        }
//        new Thread(new Runnable(){
//            Drawable drawable = loadImageFromNetwork(imageUrl);
//            @Override
//            public void run() {
//
//                // post() 特别关键，就是到UI主线程去更新图片
//                FormDataSetFieldComboBox.this.post(new Runnable(){
//                    @Override
//                    public void run() {
//                        // TODO Auto-generated method stub
//                        final Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_search);
//                        rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
//                       // Drawable leftDrawable = getResources().getDrawable(R.drawable.icon_search);
//                        //leftDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
//                        FormDataSetFieldComboBox.this.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                FormDataSetFieldComboBox.this.setCompoundDrawables(drawable,null,rightDrawable,null);
//                            }
//                        });
//
//                    }}) ;
//            }
//
//        }).start()  ;





		this.setBackgroundResource(R.drawable.ymdeditbackground);
		//this.setGravity(Gravity.CENTER);
		this.setTextColor(getResources().getColor(R.color.black));
		FormDataSetFieldComboBox_old.this.setText("");

		if (mdModel == null) return;
		EFDataSet efDataSet = mdModel.getMdmDataModel().getDataSet(viewDataSetID);

		initByDataSet(efDataSet,"");
	}

	private void initByDataSet(EFDataSet dataSet,String bh){
		if (dataSet == null || bh== null) return;
		final ArrayList<String> helpStringList  = new ArrayList<>();
		for(int i=0;i<dataSet.getRowCount();i++){
			EFRowSet efRowSet = dataSet.getRowSet(i);
			String value = efRowSet.getString(viewDataSetColID ,"");
			helpStringList.add(value);
		}

		this.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {


				if (!editable) return;
				OptionPicker optionPicker = new OptionPicker(context,helpStringList);
				optionPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
					@Override
					public void onOptionPicked(int position, String option) {
						FormDataSetFieldComboBox_old.this.setText(option);

						if (mdModel == null) return;
						EFRowSet rowSet = mdModel.getMdmDataModel().getDataSet(viewDataSetID).getRowSet(position);
						mainRowSet.putObject(dataSetColID, rowSet.getString(valueDataSetColID, ""));
					}
				});
				optionPicker.show();
			}
		});

		String viewValue = "";
		for (int i = 0; i < dataSet.getRowSetList().size() ; i++) {
			EFRowSet rowSet = (EFRowSet)dataSet.getRowSetList().get(i);
			if (rowSet.getString(valueDataSetColID, null).equals(bh)) {
				viewValue = rowSet.getString(viewDataSetColID, null);
				break;
			}
		}
		setText(viewValue);

	}

	//帮助组件设置左侧图标
	private Drawable loadImageFromNetwork(String imageUrl)
	{
		Drawable drawable = null;
		try {
			// 可以在这里通过文件名来判断，是否本地有此图片
			drawable = Drawable.createFromStream(
					new URL(imageUrl).openStream(), "image.jpg");
		} catch (IOException e) {
			Log.d("test", e.getMessage());
		}
		if (drawable == null) {
			Log.d("test", "null drawable");
		} else {
			Log.d("test", "not null drawable");
		}

		return drawable ;
	}
	public String getHorizontalAlign() {
		return horizontalAlign;
	}

	public void setHorizontalAlign(String horizontalAlign) {
		this.horizontalAlign = horizontalAlign;
	}

	public String getVerticalAlign() {
		return verticalAlign;
	}

	public void setVerticalAlign(String verticalAlign) {
		this.verticalAlign = verticalAlign;
	}

	@Override
	public void setDataSetID(String dataSetID) {
		this.dataSetID = dataSetID;
	}

	@Override
	public String getDataSetColID() {
		return dataSetColID;
	}

	@Override
	public void setDataSetColID(String dataSetColID) {
		this.dataSetColID = dataSetColID;
	}

	@Override
	public String getDataSetNameColID() {
		return null;
	}

	@Override
	public void setDataSetNameColID(String value) {

	}

	@Override
	public String getInternalDataSetID() {
		return null;
	}

	@Override
	public void setInternalDataSetID(String dataSetID) {

	}



	@Override
	public Boolean getIsUserInternalDataSetID() {
		return null;
	}

	@Override
	public void setIsUserInternalDataSetID(Boolean v) {

	}

	@Override
	public String getIdentifier() {
		return null;
	}

	@Override
	public Object getPropertyMap() {
		return null;
	}

	@Override
	public void setPropertyMap(Object value) {

	}

	@Override
	public Object getProperty(String key, Object defVal) {
		return null;
	}

	@Override
	public void setProperty(String key, Object value) {

	}

	@Override
	public int getNumberPrecision() {
		return 0;
	}

	@Override
	public void seNumberPrecision(int value) {

	}

	@Override
	public String getNumberFormat() {
		return null;
	}

	@Override
	public void setNumberFormat(String numberFormat) {

	}

	@Override
	public String getColumnType() {
		return null;
	}

	@Override
	public void setColumnType(String value) {

	}

	@Override
	public String getEditorType() {
		return null;
	}

	@Override
	public void setEditorType(String value) {

	}

	@Override
	public String getDateFormat() {
		return null;
	}

	@Override
	public void setDateFormat(String dateFormat) {

	}

	@Override
	public String getFormulaOne() {
		return null;
	}

	@Override
	public void setFormulaOne(String formulaOne) {

	}

	@Override
	public String getEditMask() {
		return null;
	}

	@Override
	public void setEditMask(String editMask) {

	}

	@Override
	public String getFkeyID() {
		return null;
	}

	@Override
	public void setFkeyID(String fkey) {

	}

	@Override
	public String getRlglID() {
		return null;
	}

	@Override
	public void setRlglID(String rlglID) {

	}

	@Override
	public String getDataSetID() {
		return dataSetID;
	}

	@Override
	public void setDataSet(EFDataSet dataSet) {
		if ( this.dataSet != dataSet ) {
			if ( this.dataSet != null ) this.dataSet.removeDataSetListener(this);
			this.dataSet = dataSet;
			if ( this.dataSet != null ) this.dataSet.addDataSetListener(this);
			this.dataChanged(dataSet);
		}

	}

	@Override
	public EFDataSet getDataSet() {
		return dataSet;
	}

	@Override
	public EFRowSet getMainRowSet() {
		return mainRowSet;
	}

	@Override
	public void dataSetChanged(DataSetEvent event) {
		dataChanged(event.getDataSet());
	}

	@Override
	public String getID() {
		return id;
	}

	@Override
	public void setID(String id) {
		this.id = id;
	}

	@Override
	public int getGap() {
		return gap;
	}

	@Override
	public void setGap(int gap) {
		this.gap = gap;
	}

	@Override
	public void setWidth(int width) {
		this.width = width;
	}

	@Override
	public void setHeight(int height) {
		this.height = height;
	}

	@Override
	public int getPercentWidth() {
		return percentWidth;
	}

	@Override
	public void setPercentWidth(int percentW) {
		percentWidth = percentW;
	}

	@Override
	public int getPercentHeight() {
		return percentHeight;
	}

	@Override
	public void setPercentHeight(int percentH) {
		percentHeight = percentH;
	}

	@Override
	public ViewSize getViewSize() {
		return size;
	}

	@Override
	public void setViewSize(ViewSize size) {
		this.size = size;
	}

	@Override
	public void setCompWidth(int width) {
		this.width = width;
	}

	@Override
	public int getCompWidth(){
		return this.width;
	}

	@Override
	public void setCompHeight(int height) {
		this.height = height;
	}

	@Override
	public int getCompHeight() {
		return this.height;
	}

	public MDModel getMdModel() {
		return mdModel;
	}

	public void setMdModel(MDModel mdModel) {
		this.mdModel = mdModel;
		mdModel.insertDMComponent(this);
	}

	@Override
	public String getValueDataSetColID() {
		return valueDataSetColID;
	}

	@Override
	public void setValueDataSetColID(String valueDataSetColID) {
		this.valueDataSetColID = valueDataSetColID;
	}

	@Override
	public String getViewDataSetColID() {
		return viewDataSetColID;
	}

	@Override
	public void setViewDataSetColID(String viewDataSetColID) {
		this.viewDataSetColID = viewDataSetColID;
	}

	@Override
	public String getViewDataSetID() {
		return viewDataSetID;
	}

	@Override
	public void setViewDataSetID(String viewDataSetID) {
		this.viewDataSetID = viewDataSetID;
	}

	private String id;
	private int x = 0;
	private int y = 0;
	private boolean enabled;
	private String toolTip;
	private boolean visible;
	private int width;
	private int height;
	private int percentWidth;
	private int percentHeight;

	public void setId(String id) {
		this.id = id;
	}



	public void setX(int x) {
		this.x = x;
	}

	public void setY(int y) {
		this.y = y;
	}




	public Boolean getEnabled() {
		return enabled;
	}

	public String getToolTip(String a) {
		return toolTip;
	}

	public Boolean getVisible() {
		return visible;
	}

	public void setVisible(Boolean visible) {
		this.visible = visible;
	}



	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
		super.setEnabled(enabled);
	}

	public void setToolTip(String toolTip) {
		this.toolTip = toolTip;
	}




	//不可输入状态时，确定是否点击整个组件下拉 true->点击整个组件下拉
	private boolean isClickInputOpenList = false;
	public boolean isClickInputOpenList() {
		return isClickInputOpenList;
	}


	@Override
	public IUIComponent getParentComp() {
		return parentComp;
	}

	@Override
	public void setParentComp(IUIComponent comp) {
		parentComp = comp;
	}


    private class DownloadImageTask extends AsyncTask<String, Void, Drawable>
    {


        protected Drawable doInBackground(String... urls) {
            Drawable drawable = loadImageFromNetwork(urls[0]);
            return drawable;
        }

        protected void onPostExecute(Drawable result) {
          //  mImageView.setImageDrawable(result);
            final Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_help_search);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            result.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            // Drawable leftDrawable = getResources().getDrawable(R.drawable.icon_search);
            //leftDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            FormDataSetFieldComboBox_old.this.setCompoundDrawables(result,null,rightDrawable,null);
//            FormDataSetFieldComboBox.this.post(new Runnable() {
//                @Override
//                public void run() {
//
//                }
//            });
        }
    }

	public Boolean getEditable() {
		return editable;
	}

	public void setEditable(Boolean editable) {
		this.editable = editable;
	}

}
